// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.api.util;

import org.w3c.dom.Document;

import javax.xml.namespace.QName;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

/**
 * Resolves a XPath to an object
 * @author web2me
 *
 */
public class XPathResolver {
	
	private String pathExpression;
	
	private Document document;
	
	XPath xpath = XPathFactory.newInstance().newXPath();
	
	public XPathResolver(){ }
	
	public XPathResolver(String pathExpression, Document document){ 
		this.pathExpression = pathExpression;
		this.document = document;
	}
	
	private XPathExpression getExpression() throws UtilityException{
		if(pathExpression == null){
			throw new UtilityException("The path expression cannot be null");
		}
		
		if(document == null){
			throw new UtilityException("The document cannot be null");
		}
		
		try {
			return xpath.compile(pathExpression);
		} catch (XPathExpressionException e) {
			throw new UtilityException("XPathExpressionException caught", e);
		}
	}
	
	/**
	 * Resolves the XPath expression as a String
	 * @return The result of evaluating the expression
	 * @throws UtilityException If an error occurs evaluating the expression
	 * @param qName The return type specified by the class <code>javax.xml.xpath.XPathConstants</code>
	 */
	public Object resolve(QName qName) throws UtilityException {
		try {
			return getExpression().evaluate(document, qName);
		} catch (XPathExpressionException e) {
			throw new UtilityException("XPathExpressionException caught", e);
		}
	}

	public String getPathExpression() {
		return pathExpression;
	}

	public void setPathExpression(String pathExpression) {
		this.pathExpression = pathExpression;
	}

	public Document getDocument() {
		return document;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

}
